Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: improved exception handling when request status code is 200 #4679

Merged
merged 1 commit into from
Oct 18, 2024

Conversation

anncwb
Copy link
Collaborator

@anncwb anncwb commented Oct 18, 2024

Description

fixed #4667

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update
  • Please, don't make changes to pnpm-lock.yaml unless you introduce a new test example.

Checklist

ℹ️ Check all checkboxes - this will indicate that you have done everything in accordance with the rules in CONTRIBUTING.

  • If you introduce new functionality, document it. You can run documentation with pnpm run docs:dev command.
  • Run the tests with pnpm test.
  • Changes in changelog are generated from PR name. Please, make sure that it explains your changes in an understandable manner. Please, prefix changeset messages with feat:, fix:, perf:, docs:, or chore:.
  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Summary by CodeRabbit

  • New Features

    • Enhanced error handling by providing a more structured error object in API requests.
    • Expanded documentation on server interactions, local development configurations, and API request examples.
  • Documentation

    • Updated guides to clarify API endpoint configurations, proxy settings, and token refreshing logic.

@anncwb anncwb added the bug Something isn't working label Oct 18, 2024
@anncwb anncwb requested review from vince292007 and a team as code owners October 18, 2024 13:50
Copy link

changeset-bot bot commented Oct 18, 2024

⚠️ No Changeset found

Latest commit: 43a1d10

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Oct 18, 2024

Walkthrough

The pull request introduces modifications to the response handling logic in the createRequestClient function across multiple files. The updates involve simplifying the destructuring of responseData to only extract code and data, removing the message field. Consequently, the error handling logic has been adjusted to throw an error object containing the entire response rather than a specific message. Additionally, documentation has been restructured to enhance clarity regarding server interactions and API configurations.

Changes

File Change Summary
apps/web-antd/src/api/request.ts Modified response handling in createRequestClient: removed message extraction, updated error handling.
apps/web-ele/src/api/request.ts Modified response handling in createRequestClient: removed message extraction, updated error handling.
apps/web-naive/src/api/request.ts Modified response handling in createRequestClient: removed message extraction, updated error handling.
playground/src/api/request.ts Modified response handling in createRequestClient: removed message extraction, updated error handling.
docs/src/en/guide/essentials/server.md Restructured content on server interaction and data mocking; added sections on local API configuration and proxy settings.
docs/src/guide/essentials/server.md Enhanced explanation of server interactions; added sections on API requests and cross-origin configurations.

Assessment against linked issues

Objective Addressed Explanation
Ensure addResponseInterceptor returns response object (Issue #4667)
Prevent string type error in error handling (Issue #4667)

Possibly related PRs

Suggested reviewers

  • vince292007

🐰 In the meadow, changes bloom,
Error handling sheds its gloom.
Code and data, clear and bright,
Simplified paths, a joyful sight!
With docs restructured, knowledge grows,
Hopping forward, as progress flows! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (6)
apps/web-naive/src/api/request.ts (1)

76-81: Improved error handling, but consider further enhancements

The changes address the core issue mentioned in #4667 by throwing a structured error object instead of a string-type error message. This allows for more detailed error information to be passed down the chain, enabling custom error handling based on the error code and message.

However, there are a few points to consider:

  1. The PR title mentions improving exception handling when the status code is 200, but there's no explicit check for this status code in the changed code.
  2. The error object structure could be more explicit. Consider structuring it like this for easier error handling downstream:
const error = { 
  response,
  code,
  message: responseData.message || 'Unknown error'
};
  1. It might be beneficial to add a comment explaining the rationale behind this change, especially mentioning how it addresses the issue with string-type error messages.

Would you like me to propose a more structured error object implementation?

apps/web-ele/src/api/request.ts (1)

77-82: Approve changes with a minor suggestion for improvement

The modifications to the response interceptor effectively address the issues mentioned in PR #4667 and align with the objectives of improving exception handling. By throwing an error object containing the entire response, you've enabled more robust error handling downstream.

However, for clarity and consistency, consider the following minor improvement:

- const error = { response };
- throw error;
+ throw new Error('Request failed', { cause: response });

This change utilizes the Error object's cause property, which is a standard way to attach additional information to errors. It maintains the ability to access the full response while providing a more structured error object.

docs/src/guide/essentials/server.md (1)

Line range hint 91-106: Remove duplicate function definitions in POST/PUT request example

The POST/PUT request example contains duplicate function definitions for saveUserApi. This redundancy might confuse readers. Consider consolidating these examples to show the different HTTP methods more clearly.

Here's a suggested revision:

import { requestClient } from '#/api/request';

// POST example
export async function createUserApi(user: UserInfo) {
  return requestClient.post<UserInfo>('/user', user);
}

// PUT example
export async function updateUserApi(user: UserInfo) {
  return requestClient.put<UserInfo>(`/user/${user.id}`, user);
}

// Combined POST/PUT example
export async function saveUserApi(user: UserInfo) {
  const url = user.id ? `/user/${user.id}` : '/user';
  return requestClient.request<UserInfo>(url, {
    data: user,
    method: user.id ? 'PUT' : 'POST',
  });
}

This revision clearly demonstrates the different ways to handle POST and PUT requests, including a combined approach.

docs/src/en/guide/essentials/server.md (3)

Line range hint 76-116: LGTM! Clear and concise API request examples.

The added examples for GET, POST, PUT, and DELETE requests using the requestClient are well-structured and provide clear guidance for developers. The use of TypeScript generics enhances type safety, which is a good practice.

Consider adding a brief comment above each example to explain its purpose, e.g., "// Example of a GET request to fetch user information". This would further improve readability and understanding for developers new to the project.


236-242: Improved error handling aligns with PR objectives.

The changes to the response processing and error handling in the createRequestClient function effectively address the issues mentioned in PR #4667. By throwing an error object containing the entire response, you ensure that subsequent error handling processes receive structured error information rather than a string-type error message.

Consider adding a custom error class to provide more context and maintain consistency in error handling across the application. For example:

class ApiError extends Error {
  constructor(public response: any) {
    super('API Error');
    this.name = 'ApiError';
  }
}

// Then in the response interceptor:
throw new ApiError(response);

This approach would allow for more specific error handling and easier debugging.


Line range hint 301-337: Comprehensive guidance on refresh token configuration.

The new section on refresh token configuration provides clear and detailed instructions for enabling and setting up the refresh token functionality. The example code for the doRefreshToken function is well-structured and consistent with the project's architecture.

To enhance security, consider adding a note about securely storing the refresh token, possibly using HTTP-only cookies or secure storage mechanisms. Additionally, you might want to mention the importance of implementing token rotation or single-use refresh tokens to mitigate the risk of token theft.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6f3d509 and 43a1d10.

📒 Files selected for processing (6)
  • apps/web-antd/src/api/request.ts (1 hunks)
  • apps/web-ele/src/api/request.ts (1 hunks)
  • apps/web-naive/src/api/request.ts (1 hunks)
  • docs/src/en/guide/essentials/server.md (1 hunks)
  • docs/src/guide/essentials/server.md (1 hunks)
  • playground/src/api/request.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (9)
playground/src/api/request.ts (3)

77-83: Summary of changes and their impact

The modifications in this file successfully address the issue described in #4667 and align with the PR objectives. The changes improve exception handling by:

  1. Simplifying the response data destructuring.
  2. Throwing an object containing the entire response, enabling more detailed error handling downstream.

These improvements allow for custom error handling based on error codes and messages, as intended. However, to ensure a smooth transition, please:

  1. Clarify how error messages will be handled without the message field.
  2. Verify that all parts of the codebase expecting the previous error format have been updated.

Overall, these changes represent a significant improvement in error handling capabilities.


82-83: Improved error handling aligns with PR objectives.

This change addresses the issue described in #4667 by throwing an object containing the entire response instead of a formatted error message. This approach enables more detailed and custom error handling downstream, allowing access to error codes and messages as needed.

To ensure compatibility with existing error handlers, please verify that all parts of the codebase expecting the previous error format (Error ${status}: ${msg}) have been updated accordingly. You can use the following script to search for potential locations that might need updating:

#!/bin/bash
# Search for usage of the old error format
rg --type typescript 'Error.*:.*msg'

77-77: Clarify the impact of removing the message field.

The message field has been removed from the response data destructuring. While this simplifies the response handling, it may impact error reporting elsewhere in the code.

Could you please clarify:

  1. How will error messages be handled without the message field?
  2. Are there any other parts of the codebase that rely on the message field from the response?

To verify the usage of the message field, you can run the following script:

✅ Verification successful

Removal of the message field verified.

No usage of the message field from responseData was found in the codebase, ensuring that error reporting remains unaffected.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of 'message' field from response data
rg --type typescript 'const.*message.*=.*response(Data)?'

Length of output: 248


Script:

#!/bin/bash
# Search for usage of 'message' field from response data in TypeScript files
rg 'const.*message.*=.*response(Data)?' --glob '*.ts'

Length of output: 55

apps/web-ele/src/api/request.ts (1)

77-82: Verify error handling compatibility and update documentation

While the changes improve the error handling in the response interceptor, it's important to ensure compatibility with the rest of the system:

  1. Update errorMessageResponseInterceptor:
    The errorMessageResponseInterceptor should be modified to handle the new error format. Currently, it expects error?.response?.data, which should still work, but it might benefit from a more direct approach to accessing the response data.

  2. System-wide impact:
    Any code that catches errors from this client will need to be updated to handle the new error format. Ensure that all error handling code throughout the application is reviewed and updated accordingly.

  3. Documentation:
    Update the API documentation to reflect the new error handling behavior, ensuring that developers using this client are aware of the change in error format.

To assist in identifying potential areas that need updating, you can run the following command to search for error handling related to this client:

This will help identify areas in the codebase where error handling is occurring, which may need to be updated to accommodate the new error format.

apps/web-antd/src/api/request.ts (1)

77-83: Improved error handling aligns with PR objectives.

The changes to the response interceptor address the issue described in #4667 by throwing an error object containing the entire response. This approach allows for more flexible error handling downstream and ensures that a response object is returned via a Promise (by throwing it).

However, consider the following:

  1. The change in error object structure might affect error handling in other parts of the application. Ensure that all error handling code is updated accordingly.

  2. It might be beneficial to add a custom error class to provide more context and maintain consistency in error handling.

To verify the impact of these changes, please run the following script:

docs/src/guide/essentials/server.md (1)

Line range hint 1-383: Documentation updates align with code changes, minor improvements suggested

The changes to the server interaction documentation accurately reflect the modifications made to the response interceptor. The new error handling mechanism addresses the issue raised in #4667 by providing more flexibility in downstream error processing.

Key points:

  1. The response interceptor now throws an error object containing the full response, allowing for more detailed error handling.
  2. The documentation has been updated to explain these changes and their implications.

Recommendations:

  1. Address the duplicate function definitions in the POST/PUT request example as suggested in the previous comment.
  2. Consider adding a note about the potential need to sanitize error objects before logging or displaying them to users, given that they now contain the full response.

Overall, these changes improve the error handling capabilities of the system and provide clearer documentation for developers. With the suggested minor improvements, this update will significantly enhance the project's robustness and maintainability.

docs/src/en/guide/essentials/server.md (3)

Line range hint 339-359: Clear guidance on data mocking practices.

The updates to the data mocking section provide valuable clarification on the use of mock data in different environments. The emphasis on using real interfaces in production and the instructions for using Nitro in development are well-explained and align with best practices.

The inclusion of links to the Nitro documentation is helpful for developers who need more detailed information.


Line range hint 361-367: Useful instructions for disabling the mock service.

The new section on disabling the mock service provides clear and concise instructions for developers who need to switch to real API endpoints during development. This addition enhances the flexibility of the development setup and aligns well with the project's documentation objectives.

The use of an environment variable for this configuration is a good practice, allowing for easy toggling of the mock service.


Line range hint 1-367: Comprehensive update to server interaction and data mocking documentation.

The changes to this documentation file significantly improve the guidance provided for API configuration, request handling, and mock data processing. The updates effectively address the issues mentioned in PR #4667, particularly in the areas of exception handling and error object structure.

Key improvements include:

  1. Clear examples of API requests using different HTTP methods.
  2. Updated error handling in the request configuration to ensure structured error objects.
  3. Comprehensive guidance on refresh token configuration.
  4. Clarification on data mocking practices, emphasizing the use of real interfaces in production.
  5. Instructions for disabling the mock service when needed.

These changes enhance the overall quality and usefulness of the documentation, providing developers with clear and actionable information for working with the project's server interaction and data mocking features.

docs/src/guide/essentials/server.md Show resolved Hide resolved
@anncwb anncwb merged commit 240f0b5 into main Oct 18, 2024
14 checks passed
@anncwb anncwb deleted the bugfix/4675 branch October 18, 2024 14:00
GavinLucky pushed a commit to GavinLucky/vue-vben-admin that referenced this pull request Oct 23, 2024
@github-actions github-actions bot locked and limited conversation to collaborators Nov 18, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Bug: addResponseInterceptor拦截器抛出error类型错误
1 participant